//
//  NSString+Extension.m
//  SeeFM
//
//  Created by CBCT_MBP on 2018/9/27.
//  Copyright © 2018年 CBCT_MBP. All rights reserved.
//

#import "NSString+Extension.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (Extension)

#pragma mark - 正则匹配
- (NSString *)stringByConverttoBankCardFormatWithString:(NSString *)string{
    
    if (self.length < 16 || self.length > 19) {
        return nil;
    }
    
    NSString *previousStr = [self substringWithRange:NSMakeRange(0, 4)];
    NSString *startStr = [self substringWithRange:NSMakeRange(4, (self.length - 8))];
    for (NSUInteger i = 0; i < startStr.length; i++) {
        startStr = [startStr stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:string];
    }
    NSString *lastStr = [self substringFromIndex:self.length - 4];
    
    return [NSString stringWithFormat:@"%@%@%@",previousStr, startStr ,lastStr];
    
}

- (NSString *)stringByConverttoPhoneNumberFormatWithString:(NSString *)string{
    
    return [NSString stringWithFormat:@"%@ %@ %@",[string substringWithRange:NSMakeRange(0, 3)], [string substringWithRange:NSMakeRange(3, 4)], [string substringWithRange:NSMakeRange(7, 4)]];
    
}

- (BOOL)isMatchChineseAndEnglishWithPracket:(BOOL)isWithPracket{
    if (isWithPracket) {
        NSString *pattern = @"^[\u4e00-\u9fa5a-zA-Z\\(\\)\\（\\）\\<\\>\\{\\}\\｛\\｝\\《\\》\\[\\]]+$";
        return [self isMatchWithPattern:pattern];
    }else{
        return [self isMatchChineseAndEnglish];
    }
    return NO;
}

- (BOOL)isMatchChineseAndEnglish{
    NSString *pattern = @"^[\u4e00-\u9fa5a-zA-Z]+$";
    return [self isMatchWithPattern:pattern];
}

- (BOOL)isMatchChinese{
    NSString *regex = @"^[\u4e00-\u9fa5]+$";
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pre evaluateWithObject:self];
}
- (BOOL)isMatchChineseAndEnglishAndNumberAndCharacter{
    NSString *pattern = @"[a-zA-Z0-9\u4e00-\u9fa5]|[^·⁄‹›ﬁﬂ‡°·‚€￥`¡™£¢∞§¶•ªº\x22]";
    return [self isMatchWithPattern:pattern];
}

- (BOOL)isMatchBankCard{
    NSString *pattern = @"^\\d{16,19}$";
    return [self isMatchWithPattern:pattern];
}

- (BOOL)isMatchEmail{
    NSString *pattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$";
    return [self isMatchWithPattern:pattern];
}

- (BOOL)isMatchUinteger{
    NSString * pattern = @"^[1-9][0-9]*$";
    return [self isMatchWithPattern:pattern];
}

- (BOOL)isMatchIdcard{
    NSString * pattern = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    return [self isMatchWithPattern:pattern];
}

- (BOOL)isMatchChineseEnglishNumberWithCustomCharacter{
    NSString *regex = @"^[\u4e00-\u9fa5a-zA-Z0-9!！\"“”#＃\\$\\￥%&'\\(\\（\\)\\）\\*＼×\\+\\＋,，\\-\\－\\.。\\/、:：;；<《=＝>》\\?\\？@＠\\[\\【\\]\\】\\\\^_——`·\\{\\｛\\}\\｝~～ 　|｜]+$";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if ([predicate evaluateWithObject:self] == YES) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)isValidateMobile{
    NSString * pattern = @"^(13[0-9]|15[012356789]|16[6]|17[013678]|18[0-9]|14[457]|19[89])[0-9]{8}$";
    return [self isMatchWithPattern:pattern];
}

#pragma mark - 私有方法
- (BOOL)isMatchWithPattern:(NSString *)pattern{
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    if (!error) {
        NSArray *results = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
        return results.count > 0 ? YES : NO;
    }
    return NO;
}

#pragma mark - 字符串MD5加密
+ (NSString *)md5HexDigest:(NSString*)input{
    const char *value = [input UTF8String];
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (unsigned int)strlen(value), outputBuffer);
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++) {
        [outputString appendFormat:@"%02x", outputBuffer[count]];
    }
    return outputString;
}

#pragma mark - 计算rect
- (CGSize)stringWithFont:(UIFont *)font size:(CGSize)size{
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName:font,
                                 NSParagraphStyleAttributeName:paragraphStyle.copy,
                                 };
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
}

- (CGSize)stringWithFont:(UIFont *)font size:(CGSize)size lineSpacing:(CGFloat)lineSpacing{
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing = lineSpacing;
    NSDictionary *attributes = @{NSFontAttributeName:font,
                                 NSParagraphStyleAttributeName:paragraphStyle.copy,
                                 };
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
}

- (NSString *)addParameters:(NSDictionary *)parameters {
    NSMutableArray *parts = [NSMutableArray array];
    
    for (NSString *key in [parameters allKeys]) {
        NSString *part = [NSString stringWithFormat:@"%@=%@", key, [parameters valueForKey:key]];
        [parts addObject: part];
    }
    
    NSString *parametersString= [parts componentsJoinedByString:@"&"];
    
    NSString *addSuffixString = @"";
    if ([[self parseURLParameters] count] > 0) {
        addSuffixString = [NSString stringWithFormat:@"%@%@", @"&", parametersString]; // 原链接已经存在参数, 则用"&"直接拼接参数;
    } else {
        addSuffixString = [NSString stringWithFormat:@"%@%@", @"?", parametersString]; // 原链接不存在参数, 则先添加"?", 再拼接参数;
    }
    
    return [self stringByAppendingString:addSuffixString];
}

- (NSMutableDictionary *)parseURLParameters {
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) return nil;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    NSString *parametersString = [self substringFromIndex:range.location + 1];
    if ([parametersString containsString:@"&"]) {
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [parameters valueForKey:key];
            if (existValue != nil) {
                if ([existValue isKindOfClass:[NSArray class]]) {
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    [parameters setValue:items forKey:key];
                } else {
                    [parameters setValue:@[existValue, value] forKey:key];
                }
            } else {
                [parameters setValue:value forKey:key];
            }
        }
    } else {
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        if (pairComponents.count == 1) {
            return nil;
        }
        
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        if (key == nil || value == nil) {
            return nil;
        }
        [parameters setValue:value forKey:key];
    }
    
    return parameters;
}

- (NSArray *)rangesOfSubString:(NSString *)subStr {
    NSRange targetRange = NSMakeRange(0, self.length);
    NSString *tagValue = subStr;
    NSRange range = targetRange;
    NSMutableArray *rangeArr = [NSMutableArray array];
    while (true) {
        range = [self rangeOfString:tagValue options:NSLiteralSearch range:targetRange];
        if (range.location != NSNotFound) {
            [rangeArr addObject:[NSValue valueWithRange:range]];
            targetRange = NSMakeRange(NSMaxRange(range), self.length - NSMaxRange(range));
        } else {
            return rangeArr;
        }
    }
    return rangeArr;
}

-(NSString *)reviseString{
    double conversionValue = [self doubleValue];
    NSString *doubleString = [NSString stringWithFormat:@"%lf", conversionValue];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}

- (NSArray *)emo_emojiRanges
{
    __block NSMutableArray *emojiRangesArray = [NSMutableArray new];
    
    [self enumerateSubstringsInRange:NSMakeRange(0,
                                                 [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring,
                                       NSRange substringRange,
                                       NSRange enclosingRange,
                                       BOOL *stop)
     {
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs &&
             hs <= 0xdbff)
         {
             if (substring.length > 1)
             {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc &&
                     uc <= 0x1f9c0)
                 {
                     [emojiRangesArray addObject:[NSValue valueWithRange:substringRange]];
                 }
             }
         }
         else if (substring.length > 1)
         {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3 ||
                 ls == 0xfe0f ||
                 ls == 0xd83c)
             {
                 [emojiRangesArray addObject:[NSValue valueWithRange:substringRange]];
             }
         }
         else
         {
             // non surrogate
             if (0x2100 <= hs &&
                 hs <= 0x27ff)
             {
                 [emojiRangesArray addObject:[NSValue valueWithRange:substringRange]];
             }
             else if (0x2B05 <= hs &&
                      hs <= 0x2b07)
             {
                 [emojiRangesArray addObject:[NSValue valueWithRange:substringRange]];
             }
             else if (0x2934 <= hs &&
                      hs <= 0x2935)
             {
                 [emojiRangesArray addObject:[NSValue valueWithRange:substringRange]];
             }
             else if (0x3297 <= hs &&
                      hs <= 0x3299)
             {
                 [emojiRangesArray addObject:[NSValue valueWithRange:substringRange]];
             }
             else if (hs == 0xa9 ||
                      hs == 0xae ||
                      hs == 0x303d ||
                      hs == 0x3030 ||
                      hs == 0x2b55 ||
                      hs == 0x2b1c ||
                      hs == 0x2b1b ||
                      hs == 0x2b50)
             {
                 [emojiRangesArray addObject:[NSValue valueWithRange:substringRange]];
             }
         }
     }];
    
    return emojiRangesArray;
}

#pragma mark - ContainsEmoji

- (BOOL)emo_containsEmoji
{
    __block BOOL containsEmoji = NO;
    
    [self enumerateSubstringsInRange:NSMakeRange(0,
                                                 [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring,
                                       NSRange substringRange,
                                       NSRange enclosingRange,
                                       BOOL *stop)
     {
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs &&
             hs <= 0xdbff)
         {
             if (substring.length > 1)
             {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc &&
                     uc <= 0x1f9c0)
                 {
                     containsEmoji = YES;
                 }
             }
         }
         else if (substring.length > 1)
         {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3 ||
                 ls == 0xfe0f ||
                 ls == 0xd83c)
             {
                 containsEmoji = YES;
             }
         }
         else
         {
             // non surrogate
             if (0x2100 <= hs &&
                 hs <= 0x27ff)
             {
                 containsEmoji = YES;
             }
             else if (0x2B05 <= hs &&
                      hs <= 0x2b07)
             {
                 containsEmoji = YES;
             }
             else if (0x2934 <= hs &&
                      hs <= 0x2935)
             {
                 containsEmoji = YES;
             }
             else if (0x3297 <= hs &&
                      hs <= 0x3299)
             {
                 containsEmoji = YES;
             }
             else if (hs == 0xa9 ||
                      hs == 0xae ||
                      hs == 0x303d ||
                      hs == 0x3030 ||
                      hs == 0x2b55 ||
                      hs == 0x2b1c ||
                      hs == 0x2b1b ||
                      hs == 0x2b50)
             {
                 containsEmoji = YES;
             }
         }
         
         if (containsEmoji)
         {
             *stop = YES;
         }
     }];
    
    return containsEmoji;
}

#pragma mark - PureEmojiString

- (BOOL)emo_isPureEmojiString
{
    if (self.length == 0) {
        return NO;
    }
    
    __block BOOL isPureEmojiString = YES;
    
    [self enumerateSubstringsInRange:NSMakeRange(0,
                                                 [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring,
                                       NSRange substringRange,
                                       NSRange enclosingRange,
                                       BOOL *stop)
     {
         BOOL containsEmoji = NO;
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs &&
             hs <= 0xdbff)
         {
             if (substring.length > 1)
             {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc &&
                     uc <= 0x1f9c0)
                 {
                     containsEmoji = YES;
                 }
             }
         }
         else if (substring.length > 1)
         {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3 ||
                 ls == 0xfe0f ||
                 ls == 0xd83c)
             {
                 containsEmoji = YES;
             }
         }
         else
         {
             // non surrogate
             if (0x2100 <= hs &&
                 hs <= 0x27ff)
             {
                 containsEmoji = YES;
             }
             else if (0x2B05 <= hs &&
                      hs <= 0x2b07)
             {
                 containsEmoji = YES;
             }
             else if (0x2934 <= hs &&
                      hs <= 0x2935)
             {
                 containsEmoji = YES;
             }
             else if (0x3297 <= hs &&
                      hs <= 0x3299)
             {
                 containsEmoji = YES;
             }
             else if (hs == 0xa9 ||
                      hs == 0xae ||
                      hs == 0x303d ||
                      hs == 0x3030 ||
                      hs == 0x2b55 ||
                      hs == 0x2b1c ||
                      hs == 0x2b1b ||
                      hs == 0x2b50)
             {
                 containsEmoji = YES;
             }
         }
         
         if (!containsEmoji)
         {
             isPureEmojiString = NO;
             *stop = YES;
         }
     }];
    
    return isPureEmojiString;
}

#pragma mark - EmojiCount

- (NSInteger)emo_emojiCount
{
    __block NSInteger emojiCount = 0;
    
    [self enumerateSubstringsInRange:NSMakeRange(0,
                                                 [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring,
                                       NSRange substringRange,
                                       NSRange enclosingRange,
                                       BOOL *stop)
     {
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs &&
             hs <= 0xdbff)
         {
             if (substring.length > 1)
             {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc &&
                     uc <= 0x1f9c0)
                 {
                     emojiCount = emojiCount + 1;
                 }
             }
         }
         else if (substring.length > 1)
         {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3 ||
                 ls == 0xfe0f ||
                 ls == 0xd83c)
             {
                 emojiCount = emojiCount + 1;
             }
         }
         else
         {
             // non surrogate
             if (0x2100 <= hs &&
                 hs <= 0x27ff)
             {
                 emojiCount = emojiCount + 1;
             }
             else if (0x2B05 <= hs &&
                      hs <= 0x2b07)
             {
                 emojiCount = emojiCount + 1;
             }
             else if (0x2934 <= hs &&
                      hs <= 0x2935)
             {
                 emojiCount = emojiCount + 1;
             }
             else if (0x3297 <= hs &&
                      hs <= 0x3299)
             {
                 emojiCount = emojiCount + 1;
             }
             else if (hs == 0xa9 ||
                      hs == 0xae ||
                      hs == 0x303d ||
                      hs == 0x3030 ||
                      hs == 0x2b55 ||
                      hs == 0x2b1c ||
                      hs == 0x2b1b ||
                      hs == 0x2b50)
             {
                 emojiCount = emojiCount + 1;
             }
         }
     }];
    
    return emojiCount;
}

// 是否为表情
- (BOOL)isEmoji {
    const unichar high = [self characterAtIndex: 0];
    
    // Surrogate pair (U+1D000-1F77F)
    if (0xd800 <= high && high <= 0xdbff) {
        const unichar low = [self characterAtIndex: 1];
        const int codepoint = ((high - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000;
        
        return (0x1d000 <= codepoint && codepoint <= 0x1f77f);
        
        // Not surrogate pair (U+2100-27BF)
    } else {
        return (0x2100 <= high && high <= 0x27bf);
    }
}

// 移除表情后的字符串
- (instancetype)removedEmojiString {
    NSMutableString* __block buffer = [NSMutableString stringWithCapacity:[self length]];
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                              [buffer appendString:([substring isEmoji])? @"": substring];
                          }];
    
    return buffer;
}

//判断中英混合的的字符串长度
- (int)convertToInt:(NSString *)strtemp
{
    int strlength = 0;
    if (strtemp.length > 0) {
        
        for (int i=0; i<[strtemp length]; ++i) {
            // 通过string的 UTF8编码长度来判断，汉字的UTF8编码长度为 3  （a > 0x4e00 && a < 0x9fff）ASCII 编码判断不准确！
            NSRange range = NSMakeRange(i, 1);
            NSString *subString = [strtemp substringWithRange:range];
            const char    *cString = [subString UTF8String];
            // 特殊emoji
            if (cString == NULL) {
                strlength += 2;
                return strlength;
            }
            if( strlen(cString) == 3) { //判断是否为中文
                strlength += 2;
            }else {
                strlength += 1;
            }
        }
        
    }
    return strlength;
}

// 位数
-(int)totalCount {
    
    int count = 0;
    // 含表情
    if ([self emo_containsEmoji]) {
        
        // 获取表情个数
        NSInteger emojiCount = [self emo_emojiCount];
        count += emojiCount*2;
        
        // 移除表情
        NSString *removedString = [self removedEmojiString];
        
        if (removedString.length > 0) {
            
            count += [self convertToInt:removedString];
            
        }
        
        return count;
        
        // 不含表情
    }else {
        
        count += [self convertToInt:self];
        return count;
        
    }
    
}
- (NSUInteger)totalCountExceptEmoji{
    __block NSUInteger count = 0;
    // 含表情
    if ([self emo_containsEmoji]) {
        
        // 移除表情后的长度
        NSString *removedString = [self removedEmojiString];
        if (removedString.length > 0) {
            count += [self convertToIntExceptEmoji:removedString];
        }
        // 拿到所有emoji
        NSArray *emojiRanges = [self emo_emojiRanges];
        [emojiRanges enumerateObjectsUsingBlock:^(NSValue *value, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *emojiString = [self substringWithRange:value.rangeValue];
            count += emojiString.length;
        }];
        return count;
        
        // 不含表情
    }else {
        
        count += [self convertToIntExceptEmoji:self];
        return count;
        
    }
}
//判断中英混合的的字符串长度 出去表情特殊处理的  汉字按1个单位长度算
- (int)convertToIntExceptEmoji:(NSString *)strtemp
{
    int strlength = 0;
    if (strtemp.length > 0) {
        
        for (int i=0; i<[strtemp length]; ++i) {
            // 通过string的 UTF8编码长度来判断，汉字的UTF8编码长度为 3  （a > 0x4e00 && a < 0x9fff）ASCII 编码判断不准确！
            NSRange range = NSMakeRange(i, 1);
            NSString *subString = [strtemp substringWithRange:range];
            const char    *cString = [subString UTF8String];
            // 特殊emoji
            if (cString == NULL) {
                strlength += 2;
                return strlength;
            }
            if( strlen(cString) == 3) { //判断是否为中文
                strlength += 1;
            }else {
                strlength += 1;
            }
        }
        
    }
    return strlength;
}



-(NSUInteger)getLength{
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < self.length; i++) {
        unichar uc = [self characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger unicodeLength = asciiLength;
    return unicodeLength;
}
- (NSUInteger)charactorNumber
{
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    return [self charactorNumberWithEncoding:encoding];
}

- (NSUInteger)charactorNumberWithEncoding:(NSStringEncoding)encoding
{
    NSUInteger strLength = 0;
    char *p = (char *)[self cStringUsingEncoding:encoding];
    
    NSUInteger lengthOfBytes = [self lengthOfBytesUsingEncoding:encoding];
    for (int i = 0; i < lengthOfBytes; i++) {
        if (*p) {
            p++;
            strLength++;
        }
        else {
            p++;
        }
    }
    return strLength;
}

- (NSUInteger)charactorNumberForChineseSpecial
{
    NSUInteger strLength = 0;
    for(int i = 0; i < [self length]; i++) {
        int a = [self characterAtIndex:i];
        if (a >= 0x4e00 && a <= 0x9fa5) { // judging whether it is Chinese
            strLength += 2;
        } else {
            strLength += 1;
        }
    }
    return strLength;
}

/* 过滤换行后的 */
-(NSString *)linefeedString {
    if ([self containsString:@"\r\n"]) {
       return [self stringByReplacingOccurrencesOfString:@"\r\n" withString:@" "];
    }else if ([self containsString:@"\n"]) {
        return [self stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    }
    return self;
}

-(NSString *)urlAddCompnentForValue:(NSString *)value key:(NSString *)key{
    
    NSMutableString *string = [[NSMutableString alloc] initWithString:self];
    
    if (value.length == 0 || key.length == 0) {
        return string;
    }
    
    @try {
        NSRange range = [string rangeOfString:@"?"];
        if (range.location != NSNotFound) {//找到了
            //如果?是最后一个直接拼接参数
            if (string.length == (range.location + range.length)) {
                string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
            }else{//如果不是最后一个需要加&
                if([string hasSuffix:@"&"]){//如果最后一个是&,直接拼接
                    string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
                }else{//如果最后不是&,需要加&后拼接
                    string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,value]];
                }
            }
        }else{//没找到
            if([string hasSuffix:@"&"]){//如果最后一个是&,去掉&后拼接
                string = (NSMutableString *)[string substringToIndex:string.length-1];
            }
            string = (NSMutableString *)[string stringByAppendingString:[NSString stringWithFormat:@"?%@=%@",key,value]];
        }
    } @catch (NSException *exception) {
        
    } @finally {
        
    }
    
    
    return string.copy;
}

+ (NSString *)stringChangeMoneyWithStr:(NSString *)str numberStyle:(NSNumberFormatterStyle)numberStyle {
    
    // 判断是否null 若是赋值为0 防止崩溃
    if (([str isEqual:[NSNull null]] || str == nil)) {
        str = 0;
    }
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = numberStyle;
    // 注意传入参数的数据长度，可用double
    NSString *money = [formatter stringFromNumber:[NSNumber numberWithDouble:[str doubleValue]]];
    
    return money;
}


/**
 *判断一个字符串是否是一个IP地址
 **/
- (BOOL)isValidIP{
    if (self.length == 0) {
        return NO;
    }
    
    NSString *pattern = @"^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5]).(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5]).(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5]).(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    return [predicate evaluateWithObject:self];
//    NSArray *ipArray = [self componentsSeparatedByString:@"."];
//    if (ipArray.count == 4) {
//        for (NSString *ipnumberStr in ipArray) {
//            int ipnumber = [ipnumberStr intValue];
//            if (!(ipnumber>=0 && ipnumber<=255)) {
//                return NO;
//            }
//        }
//        return YES;
//    }
//    return NO;
}

@end
